const config = require('../../config')
const util = require('../../util/util')
const db = wx.cloud.database();
const app = getApp();
const MAX_LIMIT = 10

Page({
  data: {
    requesting: false,
		end: false,
		emptyShow: false,
    enableBackToTop: true,
		refreshSize: 90,
		topSize: 90,
		bottomSize: 70,
    color: '#4CA1AF',
    
    diaries: [],
    diaries_temp: "",
    diary_page: 1,
    date: '',
    datePicker: false,
    // no_more_data: false,
    search_date: "",
    search_state: false
    // search_no_more: false
  },

  refresh() {
    console.log("下拉刷新事件开始")
    this.onLoad();
  },

  // onPageScroll (e) {
  //   this.refreshScroll.onPageScroll(e)
  // },

  // refresh: function (e) {
  //   setTimeout(() => {
  //     this.refreshScroll.stopRefresh()
  //   }, 1000)
  // },

  onShow() {
    console.log("==onShow==")
    var that = this;
    // 判断是不是需要更新
    wx.getStorage({
      key: 'refresh',
      success: function (res) {
        console.log("日记页面数据更新：",res.data)
        if (res.data) {
          // 初始化页数
          that.data.diary_page = 1;
          that.onLoad();
          wx.removeStorage({
            key: 'refresh'
          })
        }
      },
    });
  },  

  onLoad() {
    console.log("==onLoad==")  
    var that = this; 
    that.setData({
			requesting: true
		}); 
    
    // 初始化页数
    that.data.diary_page = 1;
    that.setData({
      requesting: false
    });
    var page = that.data.diary_page
    db.collection('diary').where({
      _openid: app.globalData.openid
    }).orderBy('createTime','desc')
    .skip((page-1) * MAX_LIMIT)
    .limit(MAX_LIMIT)
    .get({
      success: function(res) {
        let diary_data = res.data
        // res.data 是包含以上定义的两条记录的数组
        console.log("onLoad 中数据加载",res.data)
        if (diary_data == null) {
          return;
        }
        for (let i = 0; i < diary_data.length; i++) {
          diary_data[i].minicontent = diary_data[i].content.substring(0, 20);
        }
        that.setData({
          diaries: diary_data,
          end: false
        });
      }
    })    
  },

  btn_search: function() {
    wx.navigateTo({
      url: '../diary-search/index',
    })
  },

  // 写日记
  btn_write: function () {
    wx.navigateTo({
      url: '../diary-write/index',
    })
  },

  // 查看日记详情
  showDiary: function (e) {
    var index = e.currentTarget.dataset.diary;
    var that = this;
    var diary_data = that.data.diaries[index];
    var ss = JSON.stringify(diary_data)
    util.date2JSON()
    wx.setStorage({
      key: 'diary',
      data: diary_data 
    });

    // console.log(index);
    wx.navigateTo({
      url: '../diary-edit/index',
    })
  },

  // 加载更多
  loadMore: function () {
    console.log("上拉触底事件")
    this.setData({
			requesting: true
		});
    if (this.data.end) {
      return;
    }

    var that = this;
    // 定时任务0.5s后执行
    setTimeout(function () {
      var page = that.data.diary_page + 1;
      db.collection('diary').where({
        _openid: app.globalData.openid
      }).orderBy('createTime','desc')
      .skip((page-1) * MAX_LIMIT)
      .limit(MAX_LIMIT)
      .get({
        success: function(res) {
          let diary_data = res.data
          // res.data 是包含以上定义的两条记录的数组
          console.log("上拉触底加载：",res.data)
          // 如果查询不到数据，则判定加载完成
          if (diary_data == null || diary_data.length < 1) {    
            that.setData({     
              end: true
            });        
            return;
          }
          // 页面数+1
          that.setData({
            diary_page: that.data.diary_page + 1
          });
          // 处理日记内容显示，默认只取前二十个字
          for (let i = 0; i < diary_data.length; i++) {
            diary_data[i].minicontent = diary_data[i].content.substring(0, 20);
          }
          // 新加载的数据
          var new_data = diary_data;
          // 原总的记录数
          var total_data = that.data.diaries;
          // 数据累加
          total_data = total_data.concat(new_data);
          that.setData({
            diaries: total_data,
            end: false
          });
        }
      })
    }, 1000);
  },

  /**
   * 用户点击右上角分享
   * 分享到好友
   */
  onShareAppMessage() {
    return {
      title: '我的日记',
      path: '/page/diary-list/index'
    }
  },
  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: '水滴石记',
      path: '/page/diary-list/index'
    }
  },
})
